<?php

namespace App\Store\Controllers\Goods\GoodsSend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;


use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoods;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsAllot;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsLog;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsStock;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;

use App\Store\Validate\Goods\GoodsSend\GoodsSendgoods as ValidateGoodsGoodsSendGoodsSendgoods;
use Illuminate\Support\Facades\DB;

/**
 * 赠品库存
 */
class GoodsSendgoodsStockController extends Controller
{
    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsSendgoodsStock::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 调拨---使用库存列表进行调拨
     */
    public function dodistribution(Request $request)
    {
        //审核后方可调拨
        $req_data = $request->only([
            'id','target_store_id', 'count', 'remark'
        ]);
        $Validate = new ValidateGoodsGoodsSendGoodsSendgoods('dodistribution');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsSendgoodsStock::where(['id' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if($req_data['target_store_id']==$info->store_id){
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }

        $storeinfo = SiteStore::where(['id' => $req_data['target_store_id'], 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        if($req_data['count']>$info->count){
            return response()->json(['code' => '001', 'msg' => '调拨数量不能大于库存数量']);
        }

        DB::beginTransaction();
        try {
            //增加流水记录
            GoodsSendgoodsAllot::create(
                [
                'cp_id' => $cp_id,
                'store_id' => $info->store_id,
                'target_store_id'=>$req_data['target_store_id'],
                'sn_code'=>StoreCommon::createOrderSn(),
                'sendgoods_name'=>$info->sendgoods_name,
                'goods_sn_code' => $info->goods_sn_code,
                'count'=>$req_data['count'],
                'pieceprice'=>$info->pieceprice,
                'create_at'=>time(),
                'update_at'=>time(),
                'remark'=>$req_data['remark']
                ]
            );
            GoodsSendgoodsStock::where(['id' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])
                ->update(['count'=>DB::raw('count - ' . $req_data['count'])]);   //减去库存

                GoodsSendgoodsLog::create(
                    [
                    'cp_id' => $cp_id,
                    'store_id' =>  $info->store_id,
                    'target_store_id' =>$req_data['target_store_id'],
                    'type'=>4,
                    'sn_code'=>'',
                    'sendgoods_name'=>$info->sendgoods_name,
                    'goods_sn_code' => $info->goods_sn_code,
                    'count'=>$req_data['count'],
                    'pieceprice'=>$info->pieceprice,
                    'create_at'=>time(),
                    'update_at'=>time(),
                    'remark'=>$req_data['remark']
                    ]
                );

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '调拨失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '调拨操作成功']);


    }

      /**
     * 导出
     */
    public function doexport(Request $request)
    {

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $type =$accountinfo['type']?? 0;
        
        $list = GoodsSendgoodsStock::getList($request)['list'];
        $exceldata = [];

        // 店长、店员 不能看到成本
        if($type>0&& in_array($type,[1,2])){
            $row = [
                ['start_store'=>'赠品库存信息'],
                [
                    'store_name' => '所属门店',
                    'sendgoods_name' => '赠品名称',
                    'goods_sn_code' => '货号',
                    'count' => '库存数量',
                    'update_at' => '更新时间',
                    'remark' => '备注',
                ]
            ];
        }else{
            $row = [
                ['start_store'=>'赠品库存信息'],
                [
                    'store_name' => '所属门店',
                    'sendgoods_name' => '赠品名称',
                    'goods_sn_code' => '货号',
                    'count' => '库存数量',
                    'pieceprice' => '单件成本',
                    'total_pieceprice' => '总成本',
                    'update_at' => '更新时间',
                    'remark' => '备注',
                ]
            ];
        }

        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'],
                'sendgoods_name' => $val['sendgoods_name'],
                'goods_sn_code' => $val['goods_sn_code'],
                'count' => $val['count'],
                'pieceprice' => $val['pieceprice'] / 100,
                'total_pieceprice' => $val['pieceprice']*$val['count'] / 100,
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'remark' => $val['remark'],
            ];
        }

        $filename = '赠品库存信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }




}
